import React from './react';
import ReactDom from './react-dom';
// let ThemeContext = React.createContext(); //{Provider,Consumer}


let ThemeContext = React.createContext();
// class Content extends React.Component {
//   //给类组件添加一个静态属性contextType,指向ThemeContext,然后这个组件实例上会多一个this.context = Provider.value
//   static contextType = ThemeContext;
//   render(){
//     return <div style={{margin:10,border:`5px solid ${this.context.color}`, padding:5}}>
//       content
//       <button onClick={()=>{this.context.changeColor('red')}}>红色</button>
//       <button onClick={()=>{this.context.changeColor('green')}}>绿色</button>
//     </div>
//   }
// }

function Content(){
    return <ThemeContext.Consumer>
      {
        value=>(
          <div style={{margin:'10px',border:`5px solid ${value.color}`, padding:'5px'}}>
          content
          <button onClick={()=>{value.changeColor('red')}}>红色</button>
          <button onClick={()=>{value.changeColor('green')}}>绿色</button>
        </div>
        )
      }
    </ThemeContext.Consumer>
}
class Header extends React.Component {
  render(){
    return <div style={{margin:'10px',border:`5px solid ${this.props.color}`, padding:'5px'}}>
      Header
      <Title color={this.props.color}/>
    </div>
  }
}
// class Title extends React.Component {
//   render(){
//     return <div style={{margin:10,border:`5px solid ${this.props.color}`, padding:5}}>
//       Title
//     </div>
//   }
// }

//函数式组件的话返回一个Consumer children是一个函数，参数就是 Provider的value属性
function Title(props){
  return (
    <ThemeContext.Consumer>
      {
        value=>(
          <div style={{margin:'10px',border:`5px solid ${value.color}`, padding:'5px'}}>
              Title
          </div>
        )
      }
    </ThemeContext.Consumer>
  )

}
class Main extends React.Component {
  static contextType = ThemeContext;
  render(){
    return <div style={{margin:'10px',border:`5px solid ${this.context.color}`, padding:'5px'}}>
      Main
      <Content/>
    </div>
  }
}
class Panel extends React.Component {
  state={color: 'red'}
  changeColor = (color)=>{
    this.setState({color})
  }
  render(){
    let value = {color: this.state.color,changeColor:this.changeColor}
    return <ThemeContext.Provider value={value}>
      <div style={{margin:'10px',border:`5px solid ${this.state.color}`, padding:'5px'}}>
        page
        <Header color={this.state.color}/>
        <Main color={this.state.color}/>
      </div>
    </ThemeContext.Provider>
  }
}

ReactDom.render(
  <Panel/>,
  document.getElementById('root')
)
